package com.thomas.sdk.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.thomas.sdk.manager.DebugUtility;
import com.thomas.sdk.manager.DeviceManager;
import com.thomas.sdk.wrappers.User;

/**
 * 数据库操作类
 * 
 * @author thomas
 * 
 */
public class BeClubDBHandler extends BaseDBHandler {
	private static final String TABLE_USER = "table_user";
	private static final String DBNAME = "thomas.db";
	private static final String DBPATH = Environment
			.getExternalStorageDirectory().getPath() + "/.thomas/data/";

	private static BeClubDBHandler mBeClubDBHandler;

	public static synchronized BeClubDBHandler getInstance(Context cxt) {
		if (mBeClubDBHandler == null) {
			mBeClubDBHandler = new BeClubDBHandler(cxt);
		}
		return mBeClubDBHandler;
	}

	public BeClubDBHandler(Context context) {
		super(context, getAbsolutePath(context), DBNAME, null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try {
			db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_USER + "("
					+ "_id TEXT NOT NULL , " + "_details TEXT NOT NULL , "
					+ "_status INTEGER DEFAULT 0)");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	/**
	 * 插入任务的集合
	 * 
	 * @param missions
	 */
	public void inseartMission(List<User> users) {
		SQLiteDatabase sqliteDatabase = getWritableDatabase();
		if (sqliteDatabase == null) {
			return;
		}

		if (users != null && users.size() > 0) {
			for (User user : users) {
				if (users != null) {
					String _nickName = user.getNickName();
					String _password = user.getPassword();

					ContentValues cv = new ContentValues();
					cv.put("_nickName", _nickName);
					cv.put("_password", _password);
					sqliteDatabase.insert(TABLE_USER, null, cv);
				}
			}
		}
		sqliteDatabase.close();
	}

	/**
	 * 删除已经完成的任务
	 * 
	 * @param missionId
	 * @param status
	 */
	public void deleteMission(List<String> nickNames) {
		SQLiteDatabase sqliteDatabase = getWritableDatabase();
		if (sqliteDatabase == null) {
			return;
		}
		String[] names = (String[]) nickNames.toArray();
		sqliteDatabase.delete(TABLE_USER, "_id=?", names);
	}

	/**
	 * 更新任务的状态
	 * 
	 * @param missionId
	 * @param status
	 */
	public void updateMission(String missionId, boolean status) {
		SQLiteDatabase sqliteDatabase = getWritableDatabase();
		if (sqliteDatabase == null) {
			return;
		}
		ContentValues cv = new ContentValues();
		cv.put("_status", status == true ? 1 : 0);
		String[] args = { missionId };
		sqliteDatabase.update(TABLE_USER, cv, "_id=?", args);
	}

	/**
	 * 根据id获取缓存的任务
	 * 
	 * @param missonIds
	 * @return
	 */
	public List<User> getMission(List<String> UserIds) {
		SQLiteDatabase sqliteDatabase = getWritableDatabase();
		if (sqliteDatabase == null) {
			return null;
		}
		List<User> users = new ArrayList<User>();
		if (UserIds != null && UserIds.size() > 0) {
			for (String id : UserIds) {
				String[] args = { id };
				Cursor cursor = sqliteDatabase.query(TABLE_USER, null, "_id=?",
						args, null, null, null, null);

				while (cursor != null && cursor.moveToNext()) {
					String _nickName = cursor.getString(cursor
							.getColumnIndex("_nickName"));
					String _password = cursor.getString(cursor
							.getColumnIndex("_password"));
					User user = new User(_nickName, _password);
					users.add(user);
				}

				try {
					if (cursor != null) {
						cursor.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}
		sqliteDatabase.close();
		return users;
	}

	/**
	 * 获取数据库中所有的任务
	 * 
	 * @return
	 */
	public List<User> getMission() {
		SQLiteDatabase sqliteDatabase = getWritableDatabase();
		if (sqliteDatabase == null) {
			return null;
		}
		List<User> users = new ArrayList<User>();
		Cursor cursor = sqliteDatabase.query(TABLE_USER, null, null, null,
				null, null, null, null);

		while (cursor != null && cursor.moveToNext()) {
			String _nickName = cursor.getString(cursor
					.getColumnIndex("_nickName"));
			String _password = cursor.getString(cursor
					.getColumnIndex("_password"));
			User user = new User(_nickName, _password);

			users.add(user);
		}
		try {
			if (cursor != null) {
				cursor.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return users;
	}

	/**
	 * 删除数据库中任务表
	 */
	public void deleteMission() {
		SQLiteDatabase sqliteDatabase = getWritableDatabase();
		if (sqliteDatabase == null) {
			return;
		} else {
			if (tabbleIsExist(TABLE_USER)) {
				sqliteDatabase.delete(TABLE_USER, null, null);
				DebugUtility.showLog("删除数据库成功");
			} else {
				return;
			}
		}
	}

	private static String getAbsolutePath(Context cxt) {
		String path = null;
		if (DeviceManager.isSdcardWritable(cxt)) {
			path = DBPATH;
		} else {
			path = cxt.getApplicationContext().getApplicationContext()
					.getFilesDir().getAbsolutePath();
		}
		return path;
	}

	/**
	 * 判断数据库中的表是否存在
	 * 
	 * @param tableName
	 * @return
	 */
	public boolean tabbleIsExist(String tableName) {
		boolean result = false;
		if (tableName == null) {
			return false;
		}
		SQLiteDatabase db = null;
		Cursor cursor = null;
		try {
			db = this.getReadableDatabase();
			String sql = "select count(*) as c from sqlite_master where type ='table' and name ='"
					+ tableName + "' ";
			cursor = db.rawQuery(sql, null);
			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);
				if (count > 0) {
					result = true;
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
}
